package net.ideapad.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.ideapad.data.Group;
import net.ideapad.hibernate.HibernateSessionFactory;
import net.ideapad.struts.form.GetManageGroupForm;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;

/**
 * Action class that is used to retrieve a group for editing by the
 * manageGroup.jsp
 * 
 * MyEclipse Struts Creation date: 12-16-2009
 * 
 * XDoclet definition:
 * 
 * @struts.action path="/getManageGroup" name="getManageGroupForm"
 *                input="/form/getManageGroup.jsp" scope="request"
 *                validate="true"
 * @struts.action-forward name="manageGroup" path="/form/manageGroup.jsp"
 */
public class GetManageGroupAction extends Action {
	/**
	 * Method that takes a groupID from the form and stores the group in the
	 * request for use by the manageGroup.jsp
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		GetManageGroupForm getManageGroupForm = (GetManageGroupForm) form;
		Integer groupID = getManageGroupForm.getGroupID();

		Integer userID = (Integer) request.getSession().getAttribute("userID");
		
		if (groupID != null && userID != null) {
			Session session = HibernateSessionFactory.getSession();
			session.beginTransaction();

			// Lookup the group
			Group g = (Group) session.createQuery("select g from Group g left join g.moderators as m where g.groupId = :id AND m.userId = :userID").setInteger("id", groupID).setInteger("userID", userID).uniqueResult();

			request.setAttribute("group", g);

			session.getTransaction().commit();
			HibernateSessionFactory.closeSession();
		}

		return mapping.findForward("manageGroup");
	}
}